<template>
  <div class="top-bar">
    <div class="wrap top-bar-wrap">
      <div class="l">欢迎来到叩丁狼积分商城</div>
      <div class="r">
        <ul>
          <li @click="toShowToast">
            <img width="26" class="avatar" :src="userInfo.headImg" alt="" />
            用户名：{{ userInfo.nickName }}
          </li>
          <li>我的积分：{{ userInfo.coin }}</li>
          <li>获取积分</li>
          <li>叩丁狼官网</li>
          <li class="btn" @click="toLogin" v-show="!isLogined">登录</li>
          <li class="cart-btn" v-show="isLogined">
            <img src="../assets/img/cart.png" alt="" />
            <span>购物车</span>
            <b>{{ cartTotal }}</b>
          </li>
        </ul>
      </div>
    </div>
  </div>
</template>

<script>
import { mapActions, mapMutations, mapState } from "vuex";
import { WeixinLoginAPI } from "@/request/api.js";
export default {
  data() {
    return {
      //购物车总数量
      // cartTotal: 0,
    };
  },
  // watch: {
  //   "$route.path": {
  //     handler(newVal, oldVal) {
  //       console.log("这个方法什么时候执行???", newVal, oldVal);
  //       //切换路由的时候,更新用户状态
  //       let mytoken = localStorage.getItem("x-auth-token");
  //       // if (mytoken) {
  //       //   this.chanIsShowed(true);
  //       // } else {
  //       //   this.chanIsShowed(false);
  //       // }
  //       this.chanIsShowed(Boolean(mytoken));
  //     },
  //   },
  // },
  created() {
    // console.log("执行了TopBar的created方法");
    // setTimeout(async () => {
    this.$nextTick().then(async () => {
      //如果有id就获取
      let goodsId = localStorage.getItem("goodsId");
      //微信扫码的登录核心代码:拿code置换token
      let mycode = this.$route.query.code;
      // console.log("mycode为", mycode);
      if (mycode) {
        let res = await WeixinLoginAPI({
          code: mycode,
        });
        if (res.code == 0) {
          //登录成功之后的逻辑
          //1.提示用户登录成功
          this.asyncChanIsShowToast({
            msg: "验证成功,正在登录!",
            type: "success",
          });
          //2.保存token值到localStorage中
          localStorage.setItem("x-auth-token", res["x-auth-token"]);

          //3.登录状态的切换(隐藏登录按钮展示购物车按钮,显示用户昵称头像)
          this.chanIsShowed(true);

          //4.清除浏览器地址栏上面的code
          if (goodsId) {
            // console.log(goodsId);
            this.$router.push(`/details?id=${goodsId}`);
          } else {
            this.$router.push(this.$route.path);
          }

          //登录成功之后,发送用户信息的请求
          this.asyncChanUserInfo();

          // console.log(res.code);
        } else if (res.code == 400) {
          //code过期的情况
          //提示用户重新扫码
          this.asyncChanIsShowToast({
            msg: "二维码已经失效,请重新扫码登录",
            type: "danger",
          });
          //把登录的模态窗口打开
          this.chanIsShowLoginModal(true);
        } else if (res.code == 407) {
          //用户的微信还没有在这个网站上绑定手机
          //让用户绑定手机就行
          //怎么绑定手机?用手机号登录 并携带uuid   后端会自动绑定
          this.asyncChanIsShowToast({
            msg: "请使用手机号绑定登录微信",
            type: "warning",
          });
          //把登录的模态窗口打开
          this.chanIsShowLoginModal(true);
          //保存uuid
          localStorage.setItem("uuid", res.uuid);
        }
      } else {
        //这是没有code的情况    就是用户没有登录的操作,或者将用户本身就已经没有登录了的
        let mytoken = localStorage.getItem("x-auth-token");
        this.chanIsShowed(Boolean(mytoken));
        if (mytoken) {
          //有登录的情况,要发送获取用户信息的请求
          this.asyncChanUserInfo();
        } else {
          //没有登录的情况
          this.initUserInfo();
        }
      }
    });
  },
  computed: {
    ...mapState({
      isLogined: (state) => state.isShowLogin.isLogined,
      cartTotal: (state) => state.userInfo.cartTotal,
      userInfo: (state) => state.userInfo.userInfo,
    }),
  },
  methods: {
    ...mapMutations({
      chanIsShowLoginModal: "ShowLoginModal/chanIsShowLoginModal",
      chanIsShowToast: "showToast/chanIsShowToast",
      chanIsShowed: "isShowLogin/chanIsShowed",
      initUserInfo: "userInfo/initUserInfo",
    }),
    ...mapActions({
      asyncChanIsShowToast: "showToast/asyncChanIsShowToast",
      asyncChanUserInfo: "userInfo/asyncChanUserInfo",
    }),
    //提示框的显示和隐藏
    toShowToast() {
      //封装的思路:
      //调用者需要什么功能
      //再去封装的内部写逻辑
      //让调用尽可能简单

      //显示与否   true仅仅只是决定了一个显示属性
      //提示文本   "登录成功"
      //提示类型   "success"   "warning"   "danger"
      this.asyncChanIsShowToast({
        msg: "登录成功!",
        type: "success",
      });
    },
    toLogin() {
      //隐藏登录模态窗口,本质上修改vuex中的isShowLoginModal的值变成true
      this.chanIsShowLoginModal(true);
      // console.log(process.env.NODE_ENV);
      // console.log(process.env.VUE_APP_BASE_URL);
    },
  },
};
</script>
 
<style lang = "less" scoped>
@import "../assets/css/global.less";
.top-bar {
  height: 40px;
  background: #242b39;
  line-height: 40px;
  color: #fffefe;
  .top-bar-wrap {
    height: 40px;

    display: flex;
    justify-content: space-between;
    .r {
      ul {
        display: flex;
        li {
          cursor: pointer;
          margin-left: 20px;
          display: flex;
          align-items: center;
          .avatar {
            border-radius: 50%;
          }
          &.btn {
            width: 124px;
            height: 40px;
            background: @base-color;
            justify-content: center;
          }
          &.cart-btn {
            width: 124px;
            height: 40px;
            background: @base-color;
            justify-content: center;
            img {
              margin-right: 10px;
            }
            b {
              width: 20px;
              height: 20px;
              line-height: 20px;
              border-radius: 50%;
              background-color: #f40;
              text-align: center;
              margin-left: 8px;
              font-size: 12px;
            }
          }
        }
      }
    }
  }
}
</style>